#!/bin/bash
blacklist=$TONE_BM_SUITE_DIR/stress-ng.blacklist

setup()
{
    systemctl status kdump || exit 1
    echo 1 > /proc/sys/kernel/panic
    echo 1 > /proc/sys/kernel/hardlockup_panic
    echo 1 > /proc/sys/kernel/softlockup_panic
    echo 60 > /proc/sys/kernel/watchdog_thresh
    echo 1200 > /proc/sys/kernel/hung_task_timeout_secs
    echo 0 > /proc/sys/kernel/hung_task_panic
    meg_file="/var/log/messages"
    cp -a $meg_file $meg_file.bak
    echo >$meg_file
}

log_file()
{
    mkdir -p "${TONE_CURRENT_RESULT_DIR}/output"
    outputpath="$TONE_CURRENT_RESULT_DIR/output/stress-ng"
}

run()
{
    log_file
    if [ -z "$STRESS_TMPDIR" ]; then
        tmp_dir=""
    else
        tmp_dir="--temp-path $STRESS_TMPDIR"
    fi
    while read line;do
        echo $line |grep '^$' && continue
        [ -z ${exclude_tmp_list} ] && exclude_tmp_list=$line || exclude_tmp_list=$exclude_tmp_list,$line
    done<$blacklist
    if [ -z ${exclude_tmp_list} ]; then
        exclude_list=""
    else
        exclude_list="-x $exclude_tmp_list"
    fi
    
    echo "###Start run class: ${class}; LOG File: ${outputpath}.run###"
    logger stress-ng --class $class --sequential $nr_task --timeout $timeout --metrics --times --verify $exclude_list $tmp_dir 2>&1 |tee ${outputpath}.run

    # check run result	
    cat ${outputpath}.run |grep -w "run completed"
    if [ $? -ne 0 ]; then
        echo "[result] Stress_run Fail"
        exit 1
    else
        echo "[result] Stress_run Pass"
    fi
    Znum=$(ps -ef | grep defunct | grep -v grep |wc -l)
    if [ $Znum -ne 0 ]; then
        echo "[result] Z_process_check Fail"
        ps -ef | grep defunct | grep -v grep
    else
        echo "[result] Z_process_check Pass"
    fi
    Dnum=$(ps -A -ostat,pid,ppid | grep -w '$i' |wc -l)
    if [ $Dnum -ne 0 ]; then
        echo "[result] D_process_check Fail"
        ps -A -ostat,pid,ppid | grep -w '$i'
    else
	echo "[result] D_process_check Pass"
    fi
    # https://bugzilla.openanolis.cn/show_bug.cgi?id=3856
    cat /var/log/messages |grep 'stress-ng' |grep -i 'error' |grep -v 'stress-ng-enosy'
    if [ $? -ne 0 ]; then
        echo "[result] messages_check Pass"
    else
        echo "[result] messages_check Fail"
    fi	
}

parse()
{
    awk -f $TONE_BM_SUITE_DIR/parse.awk
}

teardown()
{
    mv $meg_file.bak $meg_file
    exit 0
}
